import { defineStore } from "pinia";

export interface TodoItem {
  id: number;
  name: string;
  isDone: boolean;
}
export type TodoList = TodoItem[];

export interface TodoStore {
  todoList: TodoList;
}

/*
  const fn = (): xxx => {}
  function fn(): xxx {}
*/

export const useTodoStore = defineStore("todo", {
  // 类型推论，但是类型推论对于{}，[], 推论的类型没法使用
  // 定义函数的返回值类型
  state: (): TodoStore => {
    return {
      todoList: [],
    };
  },
  getters: {
    // 已完成数量
    isDoneNum(state) {
      return state.todoList.reduce((p, c) => p + (c.isDone ? 1 : 0), 0);
    },
    // 总数
    totalNum(state) {
      return state.todoList.length;
    },
  },
  actions: {
    // 获取todo
    getTodoList() {
      setTimeout(() => {
        this.todoList = [
          { id: 1, name: "吃饭", isDone: false },
          { id: 2, name: "睡觉", isDone: true },
        ];
      }, 1000);
    },
    // 添加todo
    addTodo(name: string) {
      this.todoList.push({
        id: Date.now(),
        name,
        isDone: false,
      });
    },
    // 更新todo / 单选
    updateTodo(id: number) {
      // 因为find可能找不到内容，断言一下找到的值
      const todo = this.todoList.find((todo) => todo.id === id) as TodoItem;
      todo.isDone = !todo.isDone;
    },
    // 删除todo
    delTodo(id: number) {
      this.todoList = this.todoList.filter((todo) => todo.id !== id);
    },
    // 全选&全不选
    updateAllTodo(isDone: boolean) {
      this.todoList.forEach((todo) => {
        todo.isDone = isDone;
      });
    },
    // 批量删除
    batchDelTodo() {
      this.todoList = this.todoList.filter((todo) => !todo.isDone);
    },
  },
});
